from django.db import models
from django.db import transaction
from django.db.models import Q, F
import json

import unittest

from datetime import timedelta
from django.utils import timezone

class Visitor( models.Model ):
	user_id = models.IntegerField()
	dt = models.DateTimeField( auto_now_add = True )

	@staticmethod
	def visit( user_id ):
		Visitor.objects.create( user_id = user_id )

	class Meta:
		db_table = 'visitor'

class DevMessage( models.Model ):
	user_id = models.IntegerField() # id of user
	dt = models.DateTimeField( auto_now_add = True )
	message = models.TextField()

	class Meta:
		db_table = 'dev_message'

class AdvBlock( models.Model ):
	" A class for user adverticement. "

	anket_id = models.IntegerField()

	@staticmethod
	def get():
		all_objs = AdvBlock.objects.all()

		if len( all_objs ) == 0:
			result = None
		else:
			result = all_objs[ 0 ].anket_id
		
		return result
	
	@staticmethod
	def set( anket_id ):
		objs = AdvBlock.objects.all()

		if objs != None:
			obj = objs[ 0 ]
			obj.anket_id = anket_id
			obj.save()
		else:
			AdvBlock( anket_id = anket_id ).save()
	
	class Meta:
		db_table = 'adv_block'


class SearchOffset( models.Model ):
	" Offset for search "

	user_id = models.IntegerField( primary_key = True ) # id of user
	offset = models.IntegerField( default = 0 )

	@staticmethod
	def reset( user_id ):
		SearchOffset.objects.filter( user_id = user_id ).update( offset = 0 )

	class Meta:
		db_table = 'search_offset'

class SavedScore( models.Model ):
	SCORE_CHOICES = ( ( '0', '0', ), ( '1', '1', ), )

	user_id = models.IntegerField( db_index = True ) # id of user
	contact_id = models.IntegerField()
	_score = models.CharField( max_length = 1, choices = SCORE_CHOICES )
	
	def set_score( self, score ):
		self.score = '1' if score == 1 else '0'
	
	@staticmethod
	def get_cids( user_id ):
		saved_scores = SavedScore.objects.filter( user_id = user_id )

		ids0 = []
		ids1 = []

		for item in saved_scores:
			if item._score == '0':
				ids0.append( item.contact_id )
			else:
				ids1.append( item.contact_id )
		
		return ids0, ids1
	
	@staticmethod
	def save_cids( user_id, cids0, cids1 ):
		iter_l = [ [ cids0, '0' ], [ cids1, '1' ] ]	

		for il in iter_l:
			for cid_ in il[ 0 ]:
				c, created = SavedScore.objects.get_or_create( user_id = user_id, contact_id = cid_ )
				c._score = il[ 1 ]
				c.save()


	class Meta:
		db_table = 'saved_score'
		unique_together = ( 'user_id', 'contact_id', )

class Search( models.Model ):	
	RANGE_MIN_AGE = 18
	RANGE_MAX_AGE = 70

	_AGE_DIFF = 4 # difference to init min_age, max_age

	@staticmethod
	def save_default_params( user_id, my_age, my_sex ):
		" Init params if they was not set "
		
		try:
			search_obj = Search.objects.get( user_id = user_id )
		except Search.DoesNotExist:
			search_obj = Search( user_id = user_id )

			search_obj.min_age = my_age - Search._AGE_DIFF
			search_obj.max_age = my_age + Search._AGE_DIFF
			
			if search_obj.min_age < Search.RANGE_MIN_AGE:
				search_obj.min_age = Search.RANGE_MIN_AGE					
			
			if search_obj.max_age > Search.RANGE_MAX_AGE:
				search_obj.max_age = Search.RANGE_MAX_AGE
	
			search_obj.sex = 'f' if my_sex == 'm' else 'm'

			search_obj.user_id = user_id # My user id

			search_obj.save()
		
		return search_obj


	_LIVE_IN_CHOICES = (
		( 'c', 'my_city', ),
		( 'r', 'my_region' )
	)

	_SEX_CHOICES = (
		( 'm', 'male' ),
		( 'f', 'female' )
	)

	user_id = models.IntegerField( primary_key = True ) # id of searching user
	min_age = models.SmallIntegerField()
	max_age = models.SmallIntegerField()
	live_in = models.CharField( choices = _LIVE_IN_CHOICES, max_length = 1, default = 'c' )
	sex = models.CharField( choices = _SEX_CHOICES, max_length = 1 )

	class Meta:
		db_table = 'search'		

class DatingPhrase( models.Model ):
	_SEX_CHOICES =	(	( 'm', 'male', ),
						( 'f', 'female' ),
						( 'a', 'any' ),
					)
	
	_TYPE_CHOICES =	(	( 'u', 'usual', ),
						( 'x', 'sexy', ),
						( 'c', 'user', ),
	)

	phrase = models.TextField()
	user_id = models.IntegerField( null = True ) # user who added the phrase
	companion_sex = models.CharField( max_length = 1, choices = _SEX_CHOICES, db_index = True )
	_type = models.CharField( max_length = 1, choices = _TYPE_CHOICES, db_index = True )

	@staticmethod
	def get_user_random():
		return DatingPhrase.objects.filter( _type = 'c' ).order_by( '?' )[ 0 ]

	@staticmethod
	def get_random( companion_sex, my_name, companion_name, type_, user_id = None ):
		"'sex' is my sex."

		q = ( Q( companion_sex = companion_sex ) | Q( companion_sex = 'a' ) ) & Q( _type = type_ )

		if user_id != None:
			q &= Q( user_id = user_id )

		phrases = DatingPhrase.objects.filter( q )

		if len( phrases ) == 0:
			result = None
		else:
			result = phrases.order_by( '?' )[ 0 ].phrase.format( my_name = my_name, companion_name = companion_name )
		
		return result

	class Meta:
		db_table = 'dating_phrase'
		

class Settings( models.Model ):
	user_id = models.IntegerField( primary_key = True )
	go_to_last_page = models.BooleanField( default = False )
	notified_wrong_probas = models.BooleanField( default = False )

	class Meta:
		db_table = 'settings'


		